package admin

import (
	"easyblog/logicals"
	"easyblog/models"
	"easyblog/utils/errmsg"
	"encoding/json"
	"github.com/beego/beego/v2/core/validation"
	"github.com/beego/beego/v2/server/web"
)

type TagController struct {
	web.Controller
}

// @router /admin/tag [post]
func (this *TagController)AddTag (){
	var tag models.Tag
	body := this.Ctx.Input.RequestBody
	json.Unmarshal(body,&tag)

	result := make(map[string]interface{})

	valid := validation.Validation{}
	b, _ := valid.Valid(&tag)
	if !b {
		for _, err := range valid.Errors {
			result["status"] = errmsg.ERROR
			result["message"] = err.Key + " " + err.Message
			this.Data["json"] = result
			this.ServeJSON()
			this.StopRun()
		}
	}

	code := logicals.DefaultTag.CreateTag(&tag)
	result["status"] = code
	result["message"] = errmsg.GetErrmsg(code)
	this.Data["json"] = result
	this.ServeJSON()
}

// @router /admin/tag/:id [put]
func (this *TagController)EditTag (){
	var tag models.Tag
	body := this.Ctx.Input.RequestBody
	_ = json.Unmarshal(body,&tag)
	id, _ := this.GetInt(":id")

	result := make(map[string]interface{})

	valid := validation.Validation{}
	b, _ := valid.Valid(&tag)
	if !b {
		for _, err := range valid.Errors {
			result["status"] = errmsg.ERROR
			result["message"] = err.Key + " " + err.Message
			this.Data["json"] = result
			this.ServeJSON()
			this.StopRun()
		}
	}

	code := logicals.DefaultTag.EditTag(id,&tag)
	result["status"] = code
	result["message"] = errmsg.GetErrmsg(code)
	this.Data["json"] = result
	this.ServeJSON()
}

// @router /admin/tag/:id [delete]
func (this *TagController)DeleteTag (){
	id, _ := this.GetInt(":id")

	code := logicals.DefaultTag.DeleteTag(id)
	result := map[string]interface{}{
		"status": code,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result
	this.ServeJSON()
}

// @router /admin/tag/:id [get]
func (this *TagController)GetOneTag (){
	id, _ := this.GetInt(":id")

	tag, code := logicals.DefaultTag.GetTagById(id)
	result := map[string]interface{}{
		"status": code,
		"data":tag,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result
	this.ServeJSON()
}

// @router /admin/tags [get]
func (this *TagController) GetPageTags() {
	pageSize, err := this.GetInt("pagesize")
	if pageSize < 1 || err != nil{
		pageSize = 5
	}
	pageNum, err := this.GetInt("pagenum")
	if pageNum < 1 || err != nil{
		pageNum = 1
	}

	data, total := logicals.DefaultTag.GetPageTags(pageSize, pageNum)
	code := errmsg.SUCCSE

	result := map[string]interface{}{
		"status":  code,
		"data":    data,
		"total":   total,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result

	this.ServeJSON() //返回json格式
}